<?php
/**
 * Created by PhpStorm.
 * User: HLG
 * Date: 2019/10/16
 * Time: 14:01
 */
namespace app\api\model;
use think\Request;
use think\Db;

/**
 * 商城类
 *
 * Class Goods
 * @package app\api\model
 */
class Goods extends BaseModel
{
    protected $table = 'content_classification';

    /**
     * 商品列表
     * 商品列表
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList()
    {
        $page = input('page')?:1;
        $list = $this
            ->where(['is_deleted'=>0])
            ->page($page,10)
            ->select();
        if($list){
            $status = ['code'=>1,'msg'=>'查询成功','data'=>$list];
        }else{
            $status = ['code'=>0,'msg'=>'暂无数据','data'=>''];
        }
        return $status;
    }

    /**
     * 兑换矿
     *
     * @param $user_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyGoods($user_id)
    {
        $data = input('post.');
        $goodsData = $this->where(['id'=>$data['id'],'is_deleted'=>0,'state'=>0])->find();
        if(empty($goodsData)){
            AjaxReturn(0,'商品不存在或已下架');
        }else{
            $balanceModel = new Balance();
            //判断用户矿石是否足够
            $userBalance = $balanceModel->getInfo(['uid'=>$user_id]);
            if($userBalance['mineral']<$goodsData['price']){
                AjaxReturn(0,'矿石数量不足');
            }
            $order_sn = date('YmdHis'). rand(10000000,99999999).$user_id;
            $createData = [
                'order_sn' => $order_sn,
                'price' => $goodsData['price'],
                'name' => $goodsData['name'],
                'day_num' => $goodsData['day_num'],
                'song' => $goodsData['song'],
                'xiaohao' => $goodsData['xiaohao'],
                'create_time' => time(),
                'state' => 1,
                'user_id' => $user_id,
                'end_days' => $goodsData['end_days'],
            ];
            $this->startTrans();
            $goodsOrderModel = new GoodsOrder();
            //添加订单
            $createOrderId = $goodsOrderModel->createOrder($createData);
            //扣除用户矿石数量
            $decBalance = $balanceModel->changeBalance($user_id,'mineral',$goodsData['price'],2,6,'购买矿山扣除矿石');
            $mineModel = new UserMine();
            //添加用户矿山
            $userMine = $mineModel->insertInfo(['user_id'=>$user_id,'mine_id'=>$createOrderId,'run_time'=>$goodsData['run_time']]);
            //增加用户矿工数量
            $balanceRes = $balanceModel->changeBalance($user_id,'absenteeism',$goodsData['song'],1,6,'兑换矿山赠送矿工');
            //制度
            $system = $this->addRecommendNum($user_id);
            if($createOrderId && $userMine && $balanceRes && $system && $decBalance){
                $this->commit();
                AjaxReturn(1,'购买成功');
            }else{
                $this->rollback();
                AjaxReturn(0,'兑换失败');
            }
        }
    }

    /**
     * 制度处理（提升上级等级）
     *
     * @param $user_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addRecommendNum($user_id)
    {
        $userModel = new User();
        //当前用户信息
        $userInfo = $userModel->getInfo(['id'=>$user_id]);
        //查询上级
        $userPidInfo = $userModel->getInfo(['id'=>$userInfo['pid']]);
        if(!empty($userPidInfo)){
            //判断是否参与过制度
            $systemLogModel = new SystemLog();
            $check = $systemLogModel->getInfo(['user_id'=>$userInfo['pid'],'child_id'=>$user_id]);
            if(!empty($check)){ //参与过制度
                return true;
            }else{
                //增加上级推荐人数量
                $AddPidRecommendNum = $userModel->updateNumber(['id'=>2],1,'recommend_num',1);
                //增加上级矿工数量-分销
                $balanceModel = new Balance();
                $advConfigModel = new AdvConfig();
                $advConfig = $advConfigModel->getInfo(['id'=>1]);
                $pidBalanceRes = $balanceModel->changeBalance($userInfo['pid'],'absenteeism',$advConfig['zhitui'],1,7,'直推购买矿山赠送矿工');
                //添加制度记录
                $addSystemLog = $systemLogModel->insertInfo(['user_id'=>$userInfo['pid'],'child_id'=>$user_id]);
                //给上级提升等级和返佣
                $recommend_num = $userPidInfo['recommend_num'] + 1;
                //查询等级制度规则
                $gradeModel = new Grade();
                $gradeList = $gradeModel->getList();
                $grade = [];
                foreach($gradeList as $k=>$v){
                    if($recommend_num<$v['tui']){
                        if($k==0){
                            break;
                        }else{
                            $grade = $gradeList[$k-1];
                            break;
                        }
                    }
                }
                if(!empty($grade)){ //升级
                    //上级升级
                    $userLevel = $userModel->updateInfo(['id'=>$userInfo['pid']],['lv'=>$grade['lv']]);
                }else{
                    $userLevel = true;
                }
            }
            if($AddPidRecommendNum && $pidBalanceRes && $addSystemLog && $userLevel){
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }
}